package io.geekidea.boot.test.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.geekidea.boot.framework.exception.BusinessException;
import io.geekidea.boot.framework.page.OrderByItem;
import io.geekidea.boot.framework.page.OrderMapping;
import io.geekidea.boot.framework.page.Paging;
import io.geekidea.boot.test.dto.GradesDto;
import io.geekidea.boot.test.entity.Grades;
import io.geekidea.boot.test.mapper.GradesMapper;
import io.geekidea.boot.test.query.GradesQuery;
import io.geekidea.boot.test.service.GradesService;
import io.geekidea.boot.test.vo.GradesVo;
import io.geekidea.boot.test.query.AppGradesQuery;
import io.geekidea.boot.test.vo.AppGradesVo;
import io.geekidea.boot.util.PagingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

/**
 *  服务实现类
 *
 * @author geekidea
 * @since 2025-02-19
 */
@Slf4j
@Service
public class GradesServiceImpl extends ServiceImpl<GradesMapper, Grades> implements GradesService {

    @Autowired
    private GradesMapper gradesMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addGrades(GradesDto dto) {
        Grades grades = new Grades();
        BeanUtils.copyProperties(dto, grades);
        return save(grades);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateGrades(GradesDto dto) {
        Long id = dto.getId();
        Grades grades = getById(id);
        if (grades == null) {
            throw new BusinessException("不存在");
        }
        BeanUtils.copyProperties(dto, grades);
        return updateById(grades);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteGrades(Long id) {
        return removeById(id);
    }

    @Override
    public GradesVo getGradesById(Long id) {
        return gradesMapper.getGradesById(id);
    }

    @Override
    public Paging<GradesVo> getGradesPage(GradesQuery query) {
        OrderMapping orderMapping = new OrderMapping();
        PagingUtil.handlePage(query, orderMapping, OrderByItem.desc("id"));
        List<GradesVo> list = gradesMapper.getGradesPage(query);
        Paging<GradesVo> paging = new Paging<>(list);
        return paging;
    }

    @Override
    public AppGradesVo getAppGradesById(Long id) {
        return gradesMapper.getAppGradesById(id);
    }

    @Override
    public Paging<AppGradesVo> getAppGradesPage(AppGradesQuery query) {
        OrderMapping orderMapping = new OrderMapping();
        PagingUtil.handlePage(query, orderMapping, OrderByItem.desc("id"));
        List<AppGradesVo> list = gradesMapper.getAppGradesPage(query);
        Paging<AppGradesVo> paging = new Paging<>(list);
        return paging;
    }

}
